package com.yjf.ljr.activity;

import com.yjf.ljr.R;
import com.yjf.ljr.common.CommonData;
import com.yjf.ljr.dataclass.AcountManageDataClass;
import com.yjf.ljr.dataclass.TransferDebtDataClass;
import com.yjf.ljr.dataclass.AcountManageDataClass.AcountManageDataInfo;
import com.yjf.ljr.parser.RequestBuilder.RequestObject;
import com.yjf.ljr.util.AppUtil;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

public class DebtorDeatailActivity extends IjActivity implements OnClickListener {
	private String tradeName;// 交易名称
	private String profitRate;// 年化收益率
	private String amount;// 转让金额
	private String timeLimit;// 贷款期限
	private String tradeExpireDate;// 借款到期日期
	private String transferExpireDate;// 转让时间
	private String status;// 转让状态
	private String InterestAmount;// 预计收益

	@ID("tvDebtorName")
	private TextView mTvDebtorName;// 债权标题
	@ID("tvInterestAmount")
	private TextView mTvInterestAmount;// 预计收益
	@ID("tvDetorRate")
	private TextView mTvDetorRate;// 年利华率
	@ID("tvDebtorPrice")
	private TextView mTvDebtorPrice;// 转让价格
	@ID("tvDebtorTimeLitmit")
	private TextView mTvDebtorTimeLitmit;// 剩余期限
	@ID("tvTradeExpireDate")
	private TextView mTvTradeExpireDate;// 到期时间
	@ID("tvTransferDate")
	private TextView mTvTransferDate;// 转让截止时间
	@ID("tvRepaymentMethod")
	private TextView mTvRepaymentMethod;// 还款方式
	@ID("btImmediatelyBuy")
	private Button mBtImmediatelyBuy;
	@ID("llDebtorRepaymentDetails")
	private LinearLayout mLlDebtorRepaymentDetails;// 还款详情
	private boolean isDirectInvest = true;
	private final int FLAG_INVEST_LOGIN = 1;
	private String tradeId;// 关联交易id
	@ID("llOriginalStandardDetails")
	private LinearLayout mLlOriginalStandardDetails;
	private String tradeTransferId;
	private String investAmount;// 投资金额
	private String tradeDetailId;// 关联投资id
	private String repayDivisionWay;// 还款方式
	private String applyUserId;// 申请转让用户ID
	private static final int CONFIRMATIONSUB = 3001;// 购买债券
	public static boolean buySuccess = false;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_debtor_deatail);
		initControl();
	}

	private void initControl() {
		setTitleStr("债权详情");
		setLeftBtnClick();
		tradeTransferId = getIntent().getStringExtra("tradeTransferId");
		repayDivisionWay = getIntent().getStringExtra("repayDivisionWay");
		tradeDetailId = getIntent().getStringExtra("tradeDetailId");
		investAmount = getIntent().getStringExtra("investAmount");
		tradeId = getIntent().getStringExtra("tradeId");
		applyUserId = getIntent().getStringExtra("applyUserId");

		mLlDebtorRepaymentDetails.setOnClickListener(this);
		mBtImmediatelyBuy.setOnClickListener(this);
		mLlOriginalStandardDetails.setOnClickListener(this);
		tradeName = getIntent().getStringExtra("tradeName");// 交易名称
		profitRate = getIntent().getStringExtra("profitRate");// 年化收益率
		amount = getIntent().getStringExtra("amount");// 转让金额
		timeLimit = getIntent().getStringExtra("timeLimit");// 贷款期限
		tradeExpireDate = getIntent().getStringExtra("tradeExpireDate");// 借款到期日期
		transferExpireDate = getIntent().getStringExtra("transferExpireDate");// 转让时间
		status = getIntent().getStringExtra("status");// 转让状态
		InterestAmount = getIntent().getStringExtra("InterestAmount");// 预计收益
		mTvDebtorName.setText(tradeName);
		if (!TextUtils.isEmpty(profitRate) && profitRate.contains("%")) {
			mTvDetorRate.setText(profitRate);
		} else {
			mTvDetorRate.setText(profitRate + "%");
		}
		mTvDebtorPrice.setText(AppUtil.changeMoneyCompany(amount));
		mTvDebtorTimeLitmit.setText(timeLimit);
		mTvInterestAmount.setText(InterestAmount);
		if (!TextUtils.isEmpty(tradeExpireDate) && (tradeExpireDate.length() >= 10)) {
			mTvTradeExpireDate.setText(tradeExpireDate.substring(0, 10));
		}
		if (!TextUtils.isEmpty(transferExpireDate) && (transferExpireDate.length() >= 10)) {
			mTvTransferDate.setText(transferExpireDate.substring(0, 10));
		}
		if (!TextUtils.isEmpty(status) && "转让成功".equals(status)) {
			mBtImmediatelyBuy.setText("转让完成");
			mBtImmediatelyBuy.setBackgroundResource(R.drawable.debtor_shape);
			mBtImmediatelyBuy.setEnabled(false);
			mLlDebtorRepaymentDetails.setVisibility(View.GONE);

		}
		showProgressDialog();
		new TransfersListDebtor(tradeId).execute();
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.btImmediatelyBuy:
			getInvestPromise(true);// 进行校验用户状态
			// startActivity(new Intent(mContext,
			// ConfirmationPurchaseActivity.class));
			break;
		case R.id.llDebtorRepaymentDetails:
			Intent intentr = new Intent(this, DebtorRepaymentDetailsActivity.class);
			intentr.putExtra("tradeDetailId", tradeDetailId);
			intentr.putExtra("tradeId", tradeId);
			intentr.putExtra("applyUserId", applyUserId);
			startActivity(intentr);
			break;
		case R.id.llOriginalStandardDetails:
			Intent intent = new Intent(DebtorDeatailActivity.this, ProjectDetailActivity.class);
			intent.putExtra("demandId", tradeId);
			intent.putExtra("typeID", "tradeId");
			startActivity(intent);
			break;
		default:
			break;
		}
	}

	/**
	 * 判断是否可以投资
	 */
	public void getInvestPromise(boolean isDirect) {
		showProgressDialog();
		isDirectInvest = isDirect;
		new AcountManageTask(isDirect).execute();
	}

	class AcountManageTask extends AsyncTask<Void, Void, String> {
		private AcountManageDataClass dc = new AcountManageDataClass();

		boolean isDirect;

		public AcountManageTask(boolean isDirect) {
			this.isDirect = isDirect;
		}

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
		}

		@Override
		protected String doInBackground(Void... params) {
			// TODO Auto-generated method stub
			RequestObject mObject = new RequestObject();
			mObject.method = "appAccountInfo";
			return requestDataAndGetErrorMsg(mObject, dc);
		}

		@Override
		protected void onPostExecute(String result) {
			dismissProgressDialog();
			if ("-1".equals(dc.code)) {
				loginWebview();
				return;
			}
			if (!TextUtils.isEmpty(result)) {
				showToast(result);
			} else {
				AcountManageDataInfo data = dc.accountInfo;

				String openStatus1 = getString(R.string.payment_status_on);
				String openStatus2 = getString(R.string.payment_status_active);
				final String mobile = data.mobile;
				if (TextUtils.isEmpty(data.openState)
						|| (!data.openState.equals(openStatus1) && !data.openState.equals(openStatus2))) {
					dismissProgressDialog();
					AlertDialog.Builder builder = new AlertDialog.Builder(DebtorDeatailActivity.this);
					builder.setTitle("提示");
					builder.setMessage("您的账户未激活，激活支付账户后方可充值、投资。");
					if(!TextUtils.isEmpty(mobile)) {
						builder.setPositiveButton("立即激活", new DialogInterface.OnClickListener(){

							@Override
							public void onClick(DialogInterface dialog, int which) {
								Intent intent = new Intent(DebtorDeatailActivity.this,RegistrationActiveActivity.class);
								intent.putExtra("phoneNum", mobile);
								startActivity(intent);
							}
							
						});
						builder.setNegativeButton("暂不激活", null);
					} else {
						builder.setPositiveButton("确定", null);
					}
					AlertDialog dialog = builder.create();					
					dialog.show();
					return;
				}

				Intent i = new Intent(mContext, ConfirmationPurchaseActivity.class);
				i.putExtra("profitRate", profitRate);
				i.putExtra("amount", amount);
				i.putExtra("InterestAmount", InterestAmount);
				i.putExtra("tradeTransferId", tradeTransferId);
				i.putExtra("tradeId", tradeId);
				i.putExtra("investAmount", investAmount);
				i.putExtra("tradeDetailId", tradeDetailId);
				i.putExtra("mobile", mobile);
				startActivityForResult(i, CONFIRMATIONSUB);
				// startActivityForResult(i, CommonData.REQUEST_CODE_PROJECT);
			}

		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
		// TODO Auto-generated method stub
		if (resultCode == RESULT_OK) {

			switch (requestCode) {
			case CommonData.REQUEST_CODE_LOGIN:

				break;
			case CONFIRMATIONSUB:
				// 够买返回
				if (buySuccess) {
					buySuccess = false;
					mBtImmediatelyBuy.setText("转让完成");
					mBtImmediatelyBuy.setBackgroundResource(R.drawable.debtor_shape);
					mBtImmediatelyBuy.setEnabled(false);
				}
				break;

			default:
				break;
			}

		}
		super.onActivityResult(requestCode, resultCode, intent);
	}

	public class TransfersListDebtor extends AsyncTask<Void, Void, String> {
		RequestObject mObject = new RequestObject();
		TransferDebtDataClass dc = new TransferDebtDataClass();
		private String tradeId;

		public TransfersListDebtor(String tradeId) {
			this.tradeId = tradeId;
		}

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
		}

		@Override
		protected String doInBackground(Void... params) {
			// TODO Auto-generated method stub
			mObject.method = "transfersProjectList";
			mObject.map.put("tradeDetailId", tradeDetailId);
			return requestDataAndGetErrorMsg(mObject, dc);
		}

		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			dismissProgressDialog();

			if (TextUtils.isEmpty(result)) {
				mTvRepaymentMethod.setText(dc.list.get(0).repayDivisionWay);
			} else {

			}
		}
	}
}
